package agents

import (
	"context"
	"encoding/json"
	"errors"
	"fmt"
	"github.com/cloudwego/eino/components/model"
	"github.com/cloudwego/eino/components/prompt"
	"github.com/cloudwego/eino/schema"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"strings"
)

var content = fmt.Sprintf(`
	{role}
	Given an input question, first create a syntactically correct MySQL query to run, then look at the results of the query and return the answer to the input question.
	Unless the user specifies in the question a specific number of examples to obtain, query for at most {limit} results using the LIMIT clause as per MySQL.
	You can order the results to return the most informative data in the database.
	Never query for all columns from a table.
	You must query only the columns that are needed to answer the question.
	Wrap each column name in backticks (%s) to denote them as delimited identifiers.
	Pay attention to use only the column names you can see in the tables below.
	Be careful to not query for columns that do not exist.
	Also, pay attention to which column is in which table.
	Pay attention to use CURDATE() function to get the current date, if the question involves \"today\".
	Can only perform queries and does not accept any modification or deletion functions.
	Use the following table schema info to create your SQL query:\n{ddl}\n".
	The returned content can only contain SQL statements, without explanations or other information, and should not be labeled with SQL tags.
`, "`")

type MysqlAgent struct {
	Ctx          context.Context
	SystemPrompt string // 系统提示词或系统消息
	UserPrompt   string // 用户提示词或用户消息
	Role         string
	Client       model.ChatModel
	db           *gorm.DB
	ddl          string
	IsSql        bool
}

func NewMysqlAgent(ctx context.Context, dns, userPrompt string, client model.ChatModel) (agent *MysqlAgent, err error) {
	agent = new(MysqlAgent)
	agent.db, err = gorm.Open(mysql.Open(dns))
	if err != nil {
		return
	}
	err = agent.initTablesDDL()
	if err != nil {
		return
	}
	agent.IsSql = true
	agent.Ctx = ctx
	agent.Client = client
	agent.UserPrompt = userPrompt
	agent.SystemPrompt = content
	return
}

// 获取当前数据库（具体的库）的所有表 数据结构与数据库对象定义语句
func (agent *MysqlAgent) initTablesDDL() (err error) {
	//  Migrator 接口
	tables, err := agent.db.Migrator().GetTables()
	if err != nil {
		return err
	}
	for _, table := range tables {
		tableDDLs := map[string]interface{}{}
		err = agent.db.Raw(fmt.Sprintf("show create table %s", table)).Scan(&tableDDLs).Error
		if err != nil {
			return err
		}
		agent.ddl += fmt.Sprintf("%s;\r\n", tableDDLs["Create Table"].(string))
	}
	return nil
}

func (agent *MysqlAgent) createMessages() []*schema.Message {
	template := prompt.FromMessages(schema.FString,
		schema.SystemMessage(agent.SystemPrompt),
		schema.MessagesPlaceholder("chat_history", true),
		schema.UserMessage(fmt.Sprintf("Question: %s", agent.UserPrompt)))

	vs := map[string]any{
		"role":         agent.Role,
		"ddl":          agent.ddl,
		"limit":        10,
		"chat_history": []*schema.Message{},
	}

	messages, err := template.Format(agent.Ctx, vs)
	if err != nil {
		panic(err)
	}
	return messages
}

func (agent *MysqlAgent) GetName() string {
	return agent.Role
}

func (agent *MysqlAgent) Run() {
	sql, err := agent.generate()
	if err != nil {
		return
	}
	fmt.Println(sql)
	if !agent.IsSql {
		return
	}
	t := agent.db.Begin()
	t.Set("gorm:query_option", "for read only")
	res := map[string]interface{}{}
	t.Raw(sql).Scan(res)
	t.Commit()
	by, _ := json.Marshal(res)
	fmt.Println("结果： ", string(by))
}

func (agent *MysqlAgent) generate() (sql string, err error) {
	m, err := agent.Client.Generate(agent.Ctx, agent.createMessages())
	if err != nil {
		fmt.Println(fmt.Sprintf("sql agent 执行失败: %s", err.Error()))
		return
	}
	sql = m.Content

	err = agent.check(&sql)
	if err != nil {
		fmt.Println("生成的sql有问题： ", err.Error())
		return
	}

	return
}

func (agent *MysqlAgent) check(sql *string) error {
	// 判断是否是带思考过程
	if strings.HasPrefix(*sql, "<think>") {
		l := strings.Split(*sql, "</think>")
		if len(l) > 1 {
			*sql = l[1]
		}
	}
	*sql = strings.TrimSpace(*sql)

	if strings.HasPrefix((*sql), "```sql") {
		l := strings.Split((*sql), "```sql")
		if len(l) > 1 {
			*sql = l[1]
		}
	}
	if strings.HasSuffix((*sql), "```") {
		l := strings.Split((*sql), "```")
		if len(l) > 1 {
			*sql = l[0]
		}
	}
	*sql = strings.TrimSpace(*sql)
	if *sql == "" {
		return errors.New("sql 语句错误")
	}

	return agent.db.Exec(fmt.Sprintf("explain %s", *sql)).Error
}

func (agent *MysqlAgent) ResetUserPrompt(userPrompt string) {
	agent.UserPrompt = userPrompt
}
